<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

require_once APPPATH . 'models/m_object.php';

/**
 * Модель видео
 *
 * @package CoreFramework
 * @version 1.0
 * @author Gennadiy Kozlenko
 */
class M_Video extends M_Object {
     
    /**
     * Название таблицы
     *
     * @access protected
     * @var string
     */
    var $_table = 'videos';
     
    /**
     * Кеш жанров
     *
     * @var mixed
     */
    var $_genres = null;
     
    /**
     * Кеш стран
     *
     * @var mixed
     */
    var $_countries = null;
     
    /**
     * Кеш актеров
     *
     * @var mixed
     */
    var $_actors = null;
     
    /**
     * Кеш режиссеров
     *
     * @var mixed
     */
    var $_directors = null;
     
    /**
     * Кеш torrents
     *
     * @var mixed
     */
    var $_torrents = null;
     
    /**
     * Кеш comments
     *
     * @var mixed
     */
    var $_comments = null;
     
    /**
     * Cache screenshots
     * @var array
     */
    var $_screenshots = null;
     
    /**
     * Конструктор класса
     *
     * @access public
     * @return M_Video
     */
    function M_Video() {
        parent::M_Object();
    } // end M_Video
     
    function set_id($id) {
        parent::set_id($id);
        $this->_genres = null;
        $this->_countries = null;
        $this->_actors = null;
        $this->_directors = null;
        $this->_torrents = null;
        $this->_comments = null;
        $this->_screenshots = null;
    }
     
    /**
     * Метод активации
     *
     * @access public
     * @return boolean
     */
    function activate() {
        $sql = "
         	UPDATE
            	" . $this->db->dbprefix($this->_table) . "
         	SET
            	status = 'active'
         	WHERE
            	id_video = " . $this->db->escape($this->get_id('id_video')) . " AND
            	status <> 'active'
         	LIMIT
            	1
      	";
        if (null !== $this->db->query($sql)) {
            return true;
        }
        return false;
    } // end activate
     
    /**
     * Метод приостановки меню
     *
     * @access public
     * @return boolean
     */
    function pause() {
        $sql = "
         	UPDATE
            	" . $this->db->dbprefix($this->_table) . "
         	SET
            	status = 'paused'
         	WHERE
            	id_video = " . $this->db->escape($this->get_id('id_video')) . " AND
            	status <> 'paused'
         	LIMIT
            	1
      	";
        if (null !== $this->db->query($sql)) {
            return true;
        }
        return false;
    } // end pause
     
    /**
     * Пометка видео как feature
     *
     * @access public
     * @return boolean
     */
    function mark_featured($featured = true) {
        $sql = "
         	UPDATE
            	" . $this->db->dbprefix($this->_table) . "
         	SET
            	is_featured = ?
         	WHERE
            	id_video = " . $this->db->escape($this->get_id('id_video')) . "
         	LIMIT
            	1
      	";
        if (null !== $this->db->query($sql, array($featured ? 'yes' : 'no'))) {
            return true;
        }
        return false;
    } // end mark_featured
     
    /**
     * Удаление записи
     *
     * @access protected
     */
    function _delete() {
        $sql = "
         	UPDATE
            	" . $this->db->dbprefix($this->_table) . "
         	SET
            	status = 'deleted'
         	WHERE
            	id_video = " . $this->db->escape($this->get_id('id_video')) . " AND
            	status <> 'deleted'
         	LIMIT
            	1
      	";
        if (null !== $this->db->query($sql)) {
            return true;
        }
        return false;
    } // end _delete
     
    /**
     * Получение жанров видео
     *
     * @return array
     */
    function get_genres() {
        if (is_null($this->_genres)) {
            $this->_genres = array();
            $this->db->select('g.id_genre, g.title, g.slug, g.description')
                ->from('genres g')
                ->join('video_genres vg', 'vg.id_genre = g.id_genre')
                ->where('vg.id_video', $this->get_id('id_video'))
                ->group_by('g.id_genre')
                ->order_by('g.title');
            $query = $this->db->get();
            if (0 < $query->num_rows()) {
                $this->_genres = $query->result_array();
            }
        }
        return $this->_genres;
    }
     
    /**
     * Удаление жанров
     *
     */
    function delete_genres() {
        $this->db->where('id_video', $this->get_id('id_video'))->delete('video_genres');
        $this->_genres = null;
    }
     
    /**
     * Установка жанров
     *
     * @param int $genres
     */
    function set_genres($genres) {
        $this->delete_genres();
        foreach ($genres as $id_genre) {
            $this->add_genre($id_genre);
        }
    }
     
    /**
     * Добавление жанра
     *
     * @param int $id_genre
     */
    function add_genre($id_genre) {
        $count = $this->db->from('video_genres')
            ->where('id_video', $this->get_id('id_video'))
            ->where('id_genre', $id_genre)
            ->count_all_results();
        if (0 == $count) {
            $db_data = array(
            	'id_video' => $this->get_id('id_video'),
            	'id_genre' => $id_genre
            );
            $this->db->insert('video_genres', $db_data);
        }
        $this->_genres = null;
    }
     
    /**
     * Получение стран видео
     *
     * @return array
     */
    function get_countries() {
        if (is_null($this->_countries)) {
            $this->_countries = array();
            $this->db->select('c.id_country, c.title, c.slug, c.description')
                ->from('countries c')
                ->join('video_countries vc', 'vc.id_country = c.id_country')
                ->where('vc.id_video', $this->get_id('id_video'))
                ->group_by('c.id_country')
                ->order_by('c.title');
            $query = $this->db->get();
            if (0 < $query->num_rows()) {
                $this->_countries = $query->result_array();
            }
        }
        return $this->_countries;
    }
     
    /**
     * Удаление стран
     *
     */
    function delete_countries() {
        $this->db->where('id_video', $this->get_id('id_video'))->delete('video_countries');
        $this->_countries = null;
    }
     
    /**
     * Установка стран
     *
     * @param int $countries
     */
    function set_countries($countries) {
        $this->delete_countries();
        foreach ($countries as $id_country) {
            $this->add_country($id_country);
        }
    }
     
    /**
     * Добавление страны
     *
     * @param int $id_country
     */
    function add_country($id_country) {
        $count = $this->db->from('video_countries')
            ->where('id_video', $this->get_id('id_video'))
            ->where('id_country', $id_country)
            ->count_all_results();
        if (0 == $count) {
            $db_data = array(
            	'id_video'   => $this->get_id('id_video'),
            	'id_country' => $id_country
            );
            $this->db->insert('video_countries', $db_data);
        }
        $this->_countries = null;
    }
     
    /**
     * Получение актеров
     *
     * @return array
     */
    function get_actors() {
        if (is_null($this->_actors)) {
            $this->_actors = array();
            $this->db->select('p.id_person, p.title, p.slug, p.description')
                ->from('persons p')
                ->join('video_actors va', 'va.id_person = p.id_person')
                ->where('va.id_video', $this->get_id('id_video'))
                ->group_by('p.id_person')
                ->order_by('p.title');
            $query = $this->db->get();
            if (0 < $query->num_rows()) {
                $this->_actors = $query->result_array();
            }
        }
        return $this->_actors;
    }
     
    /**
     * Удаление актеров
     *
     */
    function delete_actors() {
        $this->db->where('id_video', $this->get_id('id_video'))->delete('video_actors');
        $this->_actors = null;
    }
     
    /**
     * Установка актеров
     *
     * @param array $persons
     */
    function set_actors($persons) {
        $this->delete_actors();
        foreach ($persons as $id_person) {
            $this->add_actor($id_person);
        }
    }
     
    /**
     * Добавление актера
     *
     * @param int $id_person
     */
    function add_actor($id_person) {
        $count = $this->db->from('video_actors')
            ->where('id_video', $this->get_id('id_video'))
            ->where('id_person', $id_person)
            ->count_all_results();
        if (0 == $count) {
            $db_data = array(
            	'id_video'  => $this->get_id('id_video'),
            	'id_person' => $id_person
            );
            $this->db->insert('video_actors', $db_data);
        }
        $this->_actors = null;
    }
     
    /**
     * Получение режиссеров
     *
     * @return array
     */
    function get_directors() {
        if (is_null($this->_directors)) {
            $this->_directors = array();
            $this->db->select('p.id_person, p.title, p.slug, p.description')
                ->from('persons p')
                ->join('video_directors vd', 'vd.id_person = p.id_person')
                ->where('vd.id_video', $this->get_id('id_video'))
                ->group_by('p.id_person')
                ->order_by('p.title');
            $query = $this->db->get();
            if (0 < $query->num_rows()) {
                $this->_directors = $query->result_array();
            }
        }
        return $this->_directors;
    }
     
    /**
     * Удаление режиссеров
     *
     */
    function delete_directors() {
        $this->db->where('id_video', $this->get_id('id_video'))->delete('video_directors');
        $this->_directors = null;
    }
     
    /**
     * Установка режиссеров
     *
     * @param array $persons
     */
    function set_directors($persons) {
        $this->delete_directors();
        foreach ($persons as $id_person) {
            $this->add_director($id_person);
        }
    }
     
    /**
     * Добавление режиссера
     *
     * @param int $id_person
     */
    function add_director($id_person) {
        $count = $this->db->from('video_directors')
            ->where('id_video', $this->get_id('id_video'))
            ->where('id_person', $id_person)
            ->count_all_results();
        if (0 == $count) {
            $db_data = array(
            	'id_video'  => $this->get_id('id_video'),
            	'id_person' => $id_person
            );
            $this->db->insert('video_directors', $db_data);
        }
        $this->_directors = null;
    }
     
    /**
     * Получение screenshots
     *
     * @return array
     */
    function get_screenshots($is_limit = true) {
        if (is_null($this->_screenshots)) {
            $this->_screenshots = array();
            $this->db->select('ts.id_screenshot, ts.link, ts.image')
                ->from('torrent_screenshots ts')
                ->join('video_torrents vt', 'vt.id_torrent = ts.id_torrent')
                ->where('vt.id_video', $this->get_id('id_video'))
                ->order_by('ts.id_screenshot', 'DESC');
            if ($is_limit) {
                $this->db->limit(6);
            }
            $query = $this->db->get();
            if (0 < $query->num_rows()) {
                $this->_screenshots = $query->result_array();
            }
        }
        return $this->_screenshots;
    }
     
    /**
     * Получение torrent файлов
     *
     * @return array
     */
    function get_torrents() {
        if (is_null($this->_torrents)) {
            $this->_torrents = array();
            $this->db->select()
                ->select("
                	(
                		SELECT
                			#GROUP_CONCAT(CONCAT(ts.image, '|', ts.link) ORDER BY ts.id_screenshot DESC SEPARATOR ';')
                                        GROUP_CONCAT(ts.image ORDER BY ts.id_screenshot DESC SEPARATOR ';')
                		FROM
                			torrent_screenshots ts
                		WHERE
                			ts.id_torrent = vt.id_torrent
                	) AS screenshots_ws
                ", false)
                ->from('video_torrents vt')
                ->where('vt.id_video', $this->get_id('id_video'))
                ->order_by('vt.id_torrent', 'desc');
            $query = $this->db->get();
            if (0 < $query->num_rows()) {
                foreach ($query->result_array() as $row) {
                    $row['screenshots'] = array_filter(explode(';', $row['screenshots_ws']));
                    if (6 < count($row['screenshots'])) {
                        $row['screenshots'] = array_splice($row['screenshots'], 0, 6);
                    }
                    array_push($this->_torrents, $row);
                }
            }
        }
        return $this->_torrents;
    }
     
    /**
     * Получение комментариев
     *
     * @return array
     */
    function get_comments() {
        if (is_null($this->_comments)) {
            $this->_comments = array();
            $this->db->select('vcom.author, vcom.email, vcom.date_created, vcom.comment')
                ->from('video_comments vcom')
                ->where('vcom.id_video', $this->get_id('id_video'))
                ->where('vcom.status', 'active')
                ->order_by('vcom.date_created');
            $query = $this->db->get();
            if (0 < $query->num_rows()) {
                $this->_comments = $query->result_array();
            }
        }
        return $this->_comments;
    }
     
    /**
     * Получение рейтинга видео
     *
     * @return array
     */
    function get_rating() {
        $rating = 0;
        if (0 < $this->get('num_ratings')) {
            $rating = (float) $this->get('sum_ratings') / $this->get('num_ratings');
        }
        return $rating;
    }
     
    /**
     * Установка рейтинга
     *
     * @param int $rating
     * @param string $ip_address
     * @param string $uid
     */
    function rate($rating, $ip_address, $uid) {
        // Проверяем на возможность повышеня рейтинга
        $count = $this->db->from('video_ratings')
            ->where('uid', $uid)
            ->where('id_video', $this->get_id('id_video'))
            ->where('date_created >', mdate('%Y-%m-%d %H:%i:%s', time() - 86400))
            ->count_all_results();
        if (0 < $count) {
            // Жопа. Уже сегодня голосовали
            return false;
        }
        // Добавляем рейтинг
        $db_data = array(
         	'id_video'     => $this->get_id('id_video'),
         	'rating'       => $rating,
         	'ip_address'   => sprintf('%u', ip2long($ip_address)),
         	'uid'          => $uid,
         	'date_created' => mdate('%Y-%m-%d %H:%i:%s')
        );
        $this->db->insert('video_ratings', $db_data);
        // Обновляем рейтинг
        $sql = "
         	UPDATE
            	" . $this->db->dbprefix($this->_table) . "
         	SET
            	sum_ratings = sum_ratings + ?,
            	num_ratings = num_ratings + 1
         	WHERE
            	id_video = ?
         	LIMIT
            	1
      	";
        $this->db->query($sql, array($rating, $this->get_id('id_video')));
        $this->_load_data();
        return true;
    }
     
   /**
    * Get partner download link
    */
   function getPartnerDownloadLink() {
       $link = '';
       $this->db->select('vp.id_partner, vp.external_id')
           ->from('video_partners vp')
           ->join('partners p', 'p.id_partner = vp.id_partner', 'left')
           ->where('p.status', 'active')
           ->where('p.type', 'download')
           ->where('vp.id_video', $this->get_id('id_video'))
           ->order_by('p.position')
           ->limit(1);
       $query = $this->db->get();
       if (0 < $query->num_rows()) {
           $row = $query->row_array();
           $obj =& get_instance();
           $obj->load->model('m_partner');
           $obj->m_partner->set_id($row['id_partner']);
           $link = $obj->m_partner->getVideoLink($row['external_id']);
       }
       return $link;
   }
   
   /**
    * Get partner online link
    */
   function getPartnerOnlineLink() {
       $link = '';
       $this->db->select('vp.id_partner, vp.external_id')
           ->from('video_partners vp')
           ->join('partners p', 'p.id_partner = vp.id_partner', 'left')
           ->where('p.status', 'active')
           ->where('p.type', 'online')
           ->where('vp.id_video', $this->get_id('id_video'))
           ->order_by('p.position')
           ->limit(1);
       $query = $this->db->get();
       if (0 < $query->num_rows()) {
           $row = $query->row_array();
           $obj =& get_instance();
           $obj->load->model('m_partner');
           $obj->m_partner->set_id($row['id_partner']);
           $link = $obj->m_partner->getVideoLink($row['external_id']);
       }
       return $link;
   }
   
}
